import re

import requests.help
from rest_framework import serializers
from django_redis import get_redis_connection
from .models import *

class CreatUserSerialzier(serializers.ModelSerializer):
    """用户注册序列化器"""
    password2=serializers.CharField(write_only=True,label='确认密码')
    sms_code=serializers.CharField(label="验证码",write_only=True)
    allow=serializers.CharField(label='同意协议',write_only=True)

    class Meta:
        model=User
        fields=['id','username','password','password2','mobile','sms_code','allow']
        # 修改校验字段选项
        extra_kwargs={
            'username':{
                'min_length':5,
                'max_length':20,
                'error_messages':{ # 自定义校验出错后的信息提示
                    'min_length':'仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only':True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {  # 自定义校验出错后的信息提示
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # 单独对某一字段进行校验，手机号，二次密码，验证码，同意协议
    def validated_mobile(self,value):
        """手机号校验"""
        if not re.match(r'1[3-9]]\d{9}$',value):
            raise serializers.ValidationError('手机号格式有误')
        return value
    def validated_allow(self,value):
        """同意协议校验"""
        if value!=True:
            raise serializers.ValidationError("请同意用户协议")
        return value
    def validate(self,attrs):
        """校验密码和验证码"""
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError("两次密码不一致")
        # 校验验证码
        redis_conn=get_redis_connection('verify_codes')
        mobile=attrs['mobile']
        real_sms_code=redis_conn.get('sms_%s'%mobile)
        if real_sms_code is None or attrs['sms_code']!=real_sms_code.decode():
            raise serializers.ValidationError("验证码错误")
        return attrs
    def create(self,validated_data):
        # 将不需要的字段移除
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        password=validated_data['password']
        user=User(**validated_data)
        user.set_password(password)
        user.save()
        return user
